var express = require('express')
const models = require("../../models");
const {success, error} = require("../../utils/message");
var router = express.Router()
const Op = models.Sequelize.Op
const checkPermission = require('../../middlewares/check-permission')

// 标签列表
router.get('/', checkPermission(), async function (req, res, next) {
    let tags = await models.Tag.findAll({
        order: [
            ['id', 'ASC'],
        ],
    })
    success(res, '查询成功', {tags})
})

// 新增标签
router.post('/', checkPermission(), async function (req, res, next) {
    const name = req.body.name

    if (!name) {
        return error(res, '请填写名称')
    }

    const tagName = await models.Category.findOne({where: {name: name}})
    if (tagName) {
        return error(res, '标签名称已存在，请勿重复添加')
    }

    let tag = await models.Tag.create(req.body)
    success(res, '新增成功', {tag})
});

// 查询单条标签
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const tag = await models.Tag.findByPk(id)
    if (!tag) {
        return error(res, '当前标签不存在，无法修改')
    }

    success(res, '查询成功', {tag})
})

// 修改标签
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const name = req.body.name

    if (!name) {
        return error(res, '请填写名称')
    }

    const tag = await models.Tag.findByPk(id)
    if (!tag) {
        return error(res, '当前标签不存在，无法修改')
    }

    tag.update(req.body)
    success(res, '修改成功', {tag})
})

// 删除标签
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const tag = await models.Tag.findOne({
        where: {id: id},
        include: [{
            model: models.Product,
            as: 'products',
        }],
    })

    if (tag.products.length > 0) {
        return error(res, '当前标签下有商品，不能删除！')
    }

    tag.destroy()
    success(res, '删除成功')
})

// 批量删除
router.post('/delete_checked', checkPermission(), async function (req, res, next) {
    // console.log(req.body);return;
    await models.Tag.destroy({
        where: {
            id: {
                [Op.in]: req.body.checked_id
            }
        }
    })
    success(res, '批量删除成功')
});

module.exports = router
